﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AuditModel;
using System.IO;

namespace AuditWeb.Controllers
{
    [Authorize(Roles = "评委")]
    public class ScoreController : Controller
    {
        private AuditDBEntities db = new AuditDBEntities();
        IAnnualEventBL iaebl = new AnnualEventBL();
        IScoreBL isbl = new ScoreBL();
        IExpertJudgeBL iejbl = new ExpertJudgeBL();
        IArchiveBL iabl = new ArchiveBL();

        //
        // GET: /Score/

        public ViewResult Index()
        {
            var scores = db.Scores.Include("Archive");
            return View(scores.ToList());
        }

        //
        // GET: /Score/Details/5

        public ViewResult Details(int id)
        {
            Score score = db.Scores.Single(s => s.ID == id);
            return View(score);
        }

        //
        // GET: /Score/Create

        public ActionResult Create(string archiveid,string returnaction)
        {
            string eventid = iaebl.GetActiveEvents().FirstOrDefault().ID;
            int subjectid = (int)db.ExpertJudges.SingleOrDefault(ej => ej.SerialNumber == User.Identity.Name).SubjectID;

            ViewBag.AnnualEventId = eventid;
            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(eventid);
            ViewBag.SubjectName = db.Subjects.SingleOrDefault(s => s.Id == subjectid).Name;
            ViewBag.ArchiveID = new SelectList(db.Archives, "ID", "ID");
            Archive archive=db.Archives.SingleOrDefault(a => a.ID == archiveid);
            ViewBag.Archive = archive;

            ScorePercentage sp = db.ScorePercentages.SingleOrDefault(s => s.AnnualEventID == eventid && s.SubjectID == subjectid);
            //if (sp == null)
            //{
            //    //sp = new ScorePercentage() { AnnualEventID = eventid, SubjectID = subjectid, PercentofInstruction = 25m, PercentofDefense = 25m, PercentofMaterial = 25m, PercentofOthers = 25m };
            //    //db.ScorePercentages.AddObject(sp);
            //    //db.SaveChanges();
            //}
            ViewBag.ScorePercentage = sp;

            //check evaluation time period
            ViewBag.CanScore = true;
            ViewBag.ScorePeriod ="评分日期 "+archive.EvaluationStartDate.Value.ToShortDateString() +"至"+ archive.EvaluationDueDate.Value.ToShortDateString();
            DateTime now = DateTime.Now;
            if (now < archive.EvaluationStartDate || now > archive.EvaluationDueDate.Value.AddDays(1))
                ViewBag.CanScore = false;
            if (sp == null)
            {
                ViewBag.CanScore = false;
                ViewBag.ScorePeriod += "<br/>学科组还没有设置评分权重。";
            }

            //archiveid = archiveid.ToUpper().Trim();
            Score currentscore = isbl.GetExpertArchiveScore(User.Identity.Name, archive.ID);
            if(currentscore==null)
                currentscore = new Score() {ArchiveID=archiveid, ExpertJudgeSerialNumber=User.Identity.Name, DefenseScore=0m, InstructionScore=0m, OtherScore=0m, MaterialScore=0m, CommentFile="" };

            ViewBag.ReturnAction = returnaction;

            return View(currentscore);
        } 

        //
        // POST: /Score/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(Score score, HttpPostedFileBase comment)
        {
            string eventid = iaebl.GetActiveEvents().FirstOrDefault().ID;
            int subjectid = (int)db.ExpertJudges.SingleOrDefault(ej => ej.SerialNumber == User.Identity.Name).SubjectID;
            string archiveid = score.ArchiveID;

            //validate with score percentage
            ScorePercentage sp = db.ScorePercentages.SingleOrDefault(s => s.AnnualEventID == eventid && s.SubjectID == subjectid);
            if (sp != null)
            {
                //sp = new ScorePercentage() { AnnualEventID = eventid, SubjectID = subjectid, PercentofInstruction = 25m, PercentofDefense = 25m, PercentofMaterial = 25m, PercentofOthers = 25m };
                //db.ScorePercentages.AddObject(sp);
                //db.SaveChanges();

                if (score.InstructionScore > sp.PercentofInstruction)
                    ModelState.AddModelError("InstructionScore", string.Format(AuditResources.Score.ScoreExceedingError, sp.PercentofInstruction));
                if (score.MaterialScore > sp.PercentofMaterial)
                    ModelState.AddModelError("MaterialScore", string.Format(AuditResources.Score.ScoreExceedingError, sp.PercentofMaterial));
                if (score.DefenseScore > sp.PercentofDefense)
                    ModelState.AddModelError("DefenseScore", string.Format(AuditResources.Score.ScoreExceedingError, sp.PercentofDefense));
                if (score.OtherScore > sp.PercentofOthers)
                    ModelState.AddModelError("OtherScore", string.Format(AuditResources.Score.ScoreExceedingError, sp.PercentofOthers));

                //set subtime automaticlly
                score.SubmitTime = DateTime.Now;

                

                if (ModelState.IsValid)
                {
                    iejbl.AddScore(score);
                    //db.Scores.AddObject(score);
                    //db.SaveChanges();
                    //upload file
                    
                    if (comment != null && comment.ContentLength > 0)
                    {
                        score = db.Scores.SingleOrDefault(s => s.ID == score.ID);
                        var fileName = AuditResources.Score.CommentFile + Path.GetExtension(comment.FileName);
                        var path = Path.Combine(Server.MapPath("~/Content/commentfiles"), score.Archive.AnnualEventID, score.Archive.Subject.Name, score.Archive.ID);
                        path = Path.Combine(path, score.ExpertJudgeSerialNumber);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        if (!string.IsNullOrEmpty(score.CommentFile) && System.IO.File.Exists(Path.Combine(path, score.CommentFile)))
                        {
                            System.IO.File.Delete(Path.Combine(path, score.CommentFile));
                        }

                        path = Path.Combine(path, fileName);
                        score.CommentFile = fileName;
                        comment.SaveAs(path);
                        db.SaveChanges();
                    }
                    return RedirectToAction("MyScores", "PW");
                }
            }

            ViewBag.AnnualEventId = eventid;
            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(eventid);
            ViewBag.SubjectName = db.Subjects.SingleOrDefault(s => s.Id == subjectid).Name;
            ViewBag.ArchiveID = new SelectList(db.Archives, "ID", "ID");
            Archive archive = db.Archives.SingleOrDefault(a => a.ID == archiveid);
            ViewBag.Archive = archive;
            ViewBag.CanScore = true;
            ViewBag.ScorePeriod = "评分日期 " + archive.EvaluationStartDate.Value.ToShortDateString() + "至" + archive.EvaluationDueDate.Value.ToShortDateString();
            ViewBag.ScorePercentage = sp;
            
            return View(score);
        }
        
        //
        // GET: /Score/Edit/5
 
        //public ActionResult Edit(int id)
        //{
        //    Score score = db.Scores.Single(s => s.ID == id);
        //    ViewBag.ArchiveID = new SelectList(db.Archives, "ID", "ID", score.ArchiveID);
        //    return View(score);
        //}

        //
        // POST: /Score/Edit/5

        //[HttpPost]
        //public ActionResult Edit(Score score)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        db.Scores.Attach(score);
        //        db.ObjectStateManager.ChangeObjectState(score, EntityState.Modified);
        //        db.SaveChanges();
        //        return RedirectToAction("Index");
        //    }
        //    ViewBag.ArchiveID = new SelectList(db.Archives, "ID", "ID", score.ArchiveID);
        //    return View(score);
        //}

        //
        // GET: /Score/Delete/5
 
        //public ActionResult Delete(int id)
        //{
        //    Score score = db.Scores.Single(s => s.ID == id);
        //    return View(score);
        //}

        //
        // POST: /Score/Delete/5

        //[HttpPost, ActionName("Delete")]
        //public ActionResult DeleteConfirmed(int id)
        //{            
        //    Score score = db.Scores.Single(s => s.ID == id);
        //    db.Scores.DeleteObject(score);
        //    db.SaveChanges();
        //    return RedirectToAction("Index");
        //}

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}